package com.sk.bilibili.view.activity;

import static com.sk.bilibili.utils.StringUtils.str;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.view.View;

import androidx.annotation.NonNull;

import com.sk.bilibili.adapter.pager.search.SearchFragmentAdapter;
import com.sk.bilibili.bean.Search;
import com.sk.bilibili.callBack.TagClickCallBack;
import com.sk.bilibili.callBack.TextChangeCallBack;
import com.sk.bilibili.databinding.ActivitySearchBinding;
import com.sk.bilibili.model.activity.SearchModel;

import java.util.List;

public class SearchActivity extends BaseActivity<ActivitySearchBinding, SearchModel> implements TagClickCallBack {

    public static void start(Context context,String keyword) {
        Intent intent = new Intent(context, SearchActivity.class);
        intent.putExtra("keyword",keyword);
        context.startActivity(intent);
    }

    @Override
    protected void afterSetView() {
        model.loadData();
        initView();
        bindEvent();
        String keyword = getIntent().getStringExtra("keyword");
        if(keyword!=null)search(keyword);
    }

    private void bindEvent() {
        bind.stvShow.setClearListener(v -> model.clearHistory());
        bind.stvShow.setTagClickCallBack(this);
        bind.tvSearch.setOnClickListener(v -> search(str(bind.etSearch)));
        bind.etSearch.addTextChangedListener(new TextChangeCallBack() {
            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()==0)showTip();
            }
        });
    }

    private void showTip() {
        bind.stvShow.setVisibility(View.VISIBLE);
        bind.llShow.setVisibility(View.GONE);
    }

    private void search(String keyword) {
        bind.etSearch.setText(keyword);
        bind.etSearch.setSelection(keyword.length());
        fragmentAdapter.setKeyword(keyword);
        model.addSearchHistory(keyword);//防止多次添加必须手动添加
        showViewPager();
    }

    private SearchFragmentAdapter fragmentAdapter;

    private void showViewPager() {
        bind.llShow.setVisibility(View.VISIBLE);
        bind.stvShow.setVisibility(View.GONE);
    }

    private void initView() {
        fragmentAdapter = new SearchFragmentAdapter(getSupportFragmentManager());
        bind.vpShow.setAdapter(fragmentAdapter);
        bind.tlShow.setupWithViewPager(bind.vpShow);
        showTip();
    }

    public void loadTipSuccess(List<Search> searches) {
        bind.stvShow.setTip(searches);
    }

    public void loadHistorySuccess(List<Search> searches) {
        bind.stvShow.setHistory(searches);
    }

    @Override
    public void onTagClick(String tag) {
        search(tag);
    }

    public void clearHistorySuccess() {
        bind.stvShow.clearHistory();
    }

}